//
//  ZLViewExtension.swift
//  ZLExtension
//
//  Created by KDWL on 2023/1/9.
//

import UIKit
import SnapKit

// MARK: frame相关
public extension UIView {
    /// 宽度
    var zl_width: CGFloat {
        get {
            return self.frame.size.width
        }
        set {
            self.frame = CGRect(x: self.zl_left, y: self.zl_top, width: newValue, height: self.zl_height)
        }
    }
    /// 高度
    var zl_height: CGFloat {
        get {
            return self.frame.size.height
        }
        set {
            self.frame = CGRect(x: self.zl_left, y: self.zl_top, width: self.zl_width, height: newValue)
        }
    }
    /// 左侧
    var zl_left: CGFloat {
        get {
            return self.frame.origin.x
        }
        set {
            self.frame = CGRect(x: newValue, y: self.zl_top, width: self.zl_width, height: self.zl_height)
        }
    }
    /// 顶部
    var zl_top: CGFloat {
        get {
            return self.frame.origin.y
        }
        set {
            self.frame = CGRect(x: self.zl_left, y: newValue, width: self.zl_width, height: self.zl_height)
        }
    }
    /// 右侧
    var zl_right: CGFloat {
        get {
            return self.zl_left + self.frame.size.width
        }
        set {
            self.frame = CGRect(x: newValue - self.zl_width, y: self.zl_top, width: self.zl_width, height: self.zl_height)
        }
    }
    /// 底部
    var zl_bottom: CGFloat {
        get {
            return self.zl_top + self.frame.size.height
        }
        set {
            self.frame = CGRect(x: self.zl_left, y: newValue - self.zl_height, width: self.zl_width, height: self.zl_height)
        }
    }
    /// 中心X
    var zl_centerX: CGFloat {
        get {
            return self.center.x
        }
        set {
            self.center = CGPoint(x: newValue, y: self.zl_centerY)
        }
    }
    /// 中心X
    var zl_centerY: CGFloat {
        get {
            return self.center.y
        }
        set {
            self.center = CGPoint(x: self.zl_centerX, y: newValue)
        }
    }
    
    /// 宽高比
    func zl_aspectRatio() -> CGFloat {
        return self.zl_width / self.zl_height
    }
}

typealias ZLTapAction = () -> ()

// MARK: UI相关
public extension UIView {
    /// 圆角
    func zl_cornerRadius(_ cornerRadius: CGFloat) {
        self.layer.cornerRadius = cornerRadius
        self.layer.masksToBounds = true
    }
    /// 圆角
    func zl_border(color: UIColor? = nil, width: CGFloat = 0) {
        if color != nil {
            self.layer.borderColor = color?.cgColor
        }
        self.layer.borderWidth = width
    }
    /// 圆角
    func zl_cornerRadius(_ cornerRadius: CGFloat, corners: UIRectCorner = .allCorners) {
        let size = CGSize(width: cornerRadius, height: cornerRadius)
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: size)
        let masklayer = CAShapeLayer()
        masklayer.frame = self.bounds
        masklayer.path = path.cgPath
        self.layer.mask = masklayer
    }
    /// 插入layer
    func zl_addCornerRadiusLayer(_ cornerRadius: CGFloat, color: UIColor = ZLColor("ffffff"), corners: UIRectCorner = .allCorners, index: UInt32 = 0) {
        let size = CGSize(width: cornerRadius, height: cornerRadius)
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: size)
        let masklayer = CAShapeLayer()
        masklayer.frame = self.bounds
        masklayer.path = path.cgPath
        masklayer.fillColor = color.cgColor
        self.layer.insertSublayer(masklayer, at: index)
    }
    /// 移除所有子视图
    func zl_removeAllSubviews() {
        subviews.forEach { subview in
            subview.removeFromSuperview()
        }
    }
    /// 设置圆
    func zl_round() {
        self.layer.cornerRadius = self.zl_height / 2.0
        self.layer.masksToBounds = true
    }
    /// 渐变色
    func zl_gradient(colors: [UIColor], locations: [NSNumber]? = nil, startPoint: CGPoint = CGPoint(x: 0, y: 0), endPoint: CGPoint = CGPoint(x: 1, y: 0)) {
        let gradientLayer = CAGradientLayer()
        self.layer.insertSublayer(gradientLayer , at: 0)
        var colorArr = [CGColor]()
        for color in colors {
            colorArr.append(color.cgColor)
        }
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        gradientLayer.frame = self.bounds
        CATransaction.commit()
        gradientLayer.colors = colorArr
        gradientLayer.locations = locations
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
    }
    /// 移除渐变色
    func zl_removeGradientLayer() {
        self.layer.sublayers?.forEach({ subLayer in
            if subLayer.isKind(of: CAGradientLayer.self) {
                subLayer.removeFromSuperlayer()
            }
        })
    }
    /// 添加视图
    func zl_addSubview(_ view: UIView, _ closure: (_ make: ConstraintMaker) -> Void) {
        self.addSubview(view)
        view.snp.makeConstraints(closure)
    }
    /// 添加视图
    func zl_insertSubview(_ view: UIView, index: Int = 0, _ closure: (_ make: ConstraintMaker) -> Void) {
        self.insertSubview(view, at: index)
        view.snp.makeConstraints(closure)
    }
    /// 添加毛玻璃效果
    func zl_addBlurEffect(style: UIBlurEffect.Style = .light, alpha: CGFloat = 1) {
        let blurEffect = UIBlurEffect(style: style)
        let blurView = UIVisualEffectView(effect: blurEffect)
        blurView.alpha = alpha
        self.zl_addSubview(blurView) { make in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
    }
    /// 判断是否有滚动的view
    func zl_subviewScrolling() -> Bool {
        if self.isKind(of: UIScrollView.self) {
            let scrollview = self as! UIScrollView
            if scrollview.isDragging || scrollview.isDecelerating {
                return true
            }
        }
        for subview in self.subviews {
            if subview.zl_subviewScrolling() {
                return true
            }
        }
        return false
    }
    /// 查找第一响应者
    func zl_findFirstResponder() -> UIView? {
        if self.isFirstResponder {
            return self
        }
        for subview in subviews {
            if let responder = subview.zl_findFirstResponder() {
                return responder
            }
        }
        return nil
    }
    /// 添加阴影
    func zl_shadow(color: UIColor = ZLColor("999999"), opacity: Float = 0.5, offset: CGSize = CGSize(width: 0, height: 0)) {
        self.layer.shadowColor = color.cgColor
        self.layer.shadowOpacity = opacity
        self.layer.shadowOffset = offset
    }
    
    /// 修改所有子视图文字色
    func zl_setAllColor(view: UIView? = nil, color: UIColor) {
        var targetView = view
        if targetView == nil {
            targetView = self
        }
        if targetView!.isKind(of: UILabel.self) {
            let label = targetView as! UILabel
            label.textColor = color
        } else if targetView!.isKind(of: UIButton.self) {
            let button = targetView as! UIButton
            button.setTitleColor(color, for: .normal)
        } else if targetView!.isKind(of: UITextField.self) {
            let textField = targetView as! UITextField
            textField.textColor = color
        } else if targetView!.isKind(of: UITextView.self) {
            let textView = targetView as! UITextView
            textView.textColor = color
        }
        for subview in targetView!.subviews {
            zl_setAllColor(view: subview, color: color)
        }
    }
    /// 修改所有子视图背景色
    func zl_setAllBackgroundColor(view: UIView? = nil, color: UIColor) {
        var targetView = view
        if targetView == nil {
            targetView = self
        }
        targetView!.backgroundColor = color
        for subview in targetView!.subviews {
            zl_setAllBackgroundColor(view: subview, color: color)
        }
    }
}

// MARK: 手势相关
public extension UIView {
    /// 添加手势
    func zl_addTap(target: Any,selector: Selector) {
        self.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: target, action: selector)
        self.addGestureRecognizer(tap)
    }
    /// 添加手势
    func zl_addTap() -> UITapGestureRecognizer {
        self.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer()
        self.addGestureRecognizer(tap)
        return tap
    }
    /// 添加拖动手势
    func zl_addPan() -> UIPanGestureRecognizer {
        self.isUserInteractionEnabled = true
        let tap = UIPanGestureRecognizer()
        self.addGestureRecognizer(tap)
        return tap
    }
    /// 添加长按手势
    func zl_addLongTap() -> UILongPressGestureRecognizer {
        self.isUserInteractionEnabled = true
        let tap = UILongPressGestureRecognizer()
        self.addGestureRecognizer(tap)
        return tap
    }
}

// MARK: 方法相关
public extension UIView {
    /// 查找子视图
    func zl_getView(ofClass: String, inView: UIView? = nil) -> UIView? {
        let view = (inView != nil ? inView : self)
        if view == nil {
            return nil
        }
        if NSStringFromClass(type(of: view!)) == ofClass {
            return view
        }
        for subview in view!.subviews {
            if let foundView = zl_getView(ofClass: ofClass, inView: subview) {
                return foundView
            }
        }
        return nil
    }
    /// 获取控制器
    func zl_getViewController() -> UIViewController? {
        var nextResponder = self.next
        while nextResponder != nil {
            if let viewController = nextResponder as? UIViewController {
                return viewController
            }
            nextResponder = nextResponder?.next
        }
        return nil
    }
    /// 查找子视图
    func zl_setBackgroundColor(ofClass: String, inView: UIView? = nil, color: UIColor) {
        var targetView = inView
        if targetView == nil {
            targetView = self
        }
        targetView!.backgroundColor = color
        for subview in targetView!.subviews {
            zl_setBackgroundColor(ofClass: ofClass, inView: subview, color: color)
        }
    }
    /// 获取控制器
//    func zl_vc() -> ZLBaseVC? {
//        var responder: UIResponder? = self
//        while let r = responder {
//            if let vc = r as? UIViewController {
//                return vc
//            }
//            responder = r.next
//        }
//        return nil
//    }
}


public extension UIView {
    /// nib加载view
    /// - Parameter nibname: nib名字
    /// - Returns: 视图
    class func zl_loadFromNib<T: UIView>(nibName: String? = nil) -> T? {
        let nibName = nibName ?? String(describing: T.self)
        guard let nibView = Bundle.main.loadNibNamed(nibName, owner: self, options: nil)?.first as? UIView else {
            return nil
        }
        return (nibView as? T)
    }
}
